<template>
  <el-dropdown v-loading.fullscreen.lock="loading" :element-loading-text="loadingText" @command="handleCommand">
    <el-button v-if="type=='button'" icon="el-icon-download" type="primary" plain>
      {{ tooltip }}<i class="el-icon-arrow-down el-icon--right" />
    </el-button>
    <span v-else-if="type=='text'" class="el-dropdown-link color-primary common-cursor">
      {{ tooltip }}<i class="el-icon-arrow-down el-icon--right" />
    </span>
    <el-tooltip v-else class="item" effect="dark" :content="(tooltip?(tooltip+'->'):'')+(async?'异步':'同步')+'导出'" placement="top">
      <el-button circle icon="el-icon-download" style="margin-left: 10px;" />
    </el-tooltip>
    <el-dropdown-menu v-if="!disabled" slot="dropdown">
      <el-dropdown-item v-if="accept.indexOf('csv')>-1" command="csv">导出*.csv文件</el-dropdown-item>
      <el-dropdown-item v-if="accept.indexOf('xls')>-1" command="xls">导出*.xls文件</el-dropdown-item>
      <el-dropdown-item v-if="accept.indexOf('xls')>-1" command="xlsx">导出*.xlsx文件</el-dropdown-item>
      <el-dropdown-item v-if="accept.indexOf('json')>-1" command="json">导出*.json文件</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
export default {
  props: {
    className: {
      type: String,
      required: true
    },
    listQuery: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      required: false,
      default: 'icon'
    },
    async: {
      type: Boolean,
      required: false,
      default: false
    },
    title: {
      type: String,
      required: false,
      default: '标题'
    },
    tooltip: {
      type: String,
      required: false,
      default: ''
    },
    accept: {
      type: String,
      required: false,
      default: 'csv,xls,json'
    },
    module: {
      type: String,
      required: false,
      default: ''
    },
    actions: {
      type: Array,
      required: false,
      default: () => {
        return ['exportData', 'getExportProcessStatus']
      }
    }
  },
  data() {
    return {
      disabled: false,
      defaultModule: this.constants.UPMS,
      loading: false,
      loadingText: '正在导出...',
      realTimeProgressInterval: null,
      stepStart: 0

    }
  },
  watch: {

  },
  mounted() {
  },
  created() {
    if (this.actions.length !== 2) {
      this.msgWarning('请传递合法的Actions属性')
      this.disabled = true
    }
    if (this.module.length > 0) {
      this.defaultModule = this.module
    }
    console.log(this.defaultModule)
  },
  methods: {
    handleCommand(command) {
      this.$confirm('你确定导出' + command + '文件吗, 是否继续?', '导出提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.commandInfo = command
        this.exportData(command)
      }).catch((err) => {
        console.log(err)
        this.msgWarning('已取消执行导出操作')
      })
    },
    exportData(type) {
      this.listQuery.className = this.className // 'virtualIdentity'
      this.listQuery.exportType = type
      this.listQuery.async = this.async
      this.listQuery.module = this.defaultModule
      this.$store.dispatch(this.actions[0], this.listQuery).then(response => {
        if (this.async !== true) {
          this.downLoad(response)
        }
      }).catch((e) => {
        var $this = this
        const reader = new FileReader()
        reader.addEventListener('loadend', function() {
          var json = JSON.parse(reader.result)
          if (json.success) {
            $this.loading = true
            $this.loadingText = '正在启动下载'
            $this.stepStart = new Date().getTime()
            $this.getDealStatus(json.data)
          }
        })
        reader.readAsText(e, 'UTF-8')
      })
    },
    getDealStatus(taskId) {
      this.realTimeProgressInterval = setInterval(() => {
        this.$store.dispatch(this.actions[1], {
          taskId: taskId,
          className: this.className,
          loading: false,
          module: this.defaultModule
        }).then((res) => {
          if (this.realTimeProgressInterval) {
            clearInterval(this.realTimeProgressInterval)
          }
          this.loadingText = `任务完成，已耗时:${(new Date().getTime() - this.stepStart) / 1000}秒，即将下载`
          setTimeout(() => {
            this.loading = false
          }, 1000)
          this.downLoad(res)
        }).catch((e) => {
          var $this = this
          const reader = new FileReader()
          reader.addEventListener('loadend', function() {
            var json = JSON.parse(reader.result)
            if (json.success) {
              var result = json.data

              if (result.progress === 'ERROR') {
                console.log(result.message)
                if ($this.realTimeProgressInterval) {
                  clearInterval($this.realTimeProgressInterval)
                }
                $this.loadingText = `${result.describe}`
                setTimeout(() => {
                  $this.loading = false
                }, 2000)
              } else if (result.progress === 'FINISH') {
                $this.loadingText = `完成,已耗时:${(new Date().getTime() - $this.stepStart) / 1000}s`
                if ($this.realTimeProgressInterval) {
                  $this.loading = false
                  clearInterval($this.realTimeProgressInterval)
                }
              } else {
                $this.loadingText = `${result.describe}（已耗时:${(new Date().getTime() - $this.stepStart) / 1000}秒）`
              }
            } else {
              if ($this.realTimeProgressInterval) {
                clearInterval($this.realTimeProgressInterval)
              }
              $this.loadingText = `发生错误!`
              $this.loading = false
            }
          })
          reader.readAsText(e, 'UTF-8')
        })
      }, 1000)
    },
    downLoad(response) {
      var title = `${this.title}_${this.T.formatDate(new Date().getTime(), this.T.DATE_TIME_FMT1)}.${this.listQuery.exportType}`
      this.T.downloadFile(response, title)
    }
  }
}
</script>
<style lang="scss">
</style>
